package com.wwk.netty;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.wwk.netty.ByteBufferUtil.debugRead;

/**
 * @Author wwk
 * @DATE 2022/5/23 22:14
 */
@Slf4j
public class Server {
    /**
     * 使用nio理解阻塞
     * */
    public static void main(String[] args) throws IOException {
        //0.创建一个buffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //1.创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //非阻塞模式 false为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        //2.绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(18080));
        //3.连接集合
        List<SocketChannel> channels = new ArrayList<>();
        //可能有多个连接,希望能一直去获取连接
        while (true) {
            // 4.accept建立与客户端连接，SocketChannel用来与客户端通信
//            log.info("connecting");
            SocketChannel sc = serverSocketChannel.accept();  //阻塞线程，直到有连接
            if (sc != null) {
                log.debug("connected... {}", sc);
                sc.configureBlocking(false); // 非阻塞模式
                channels.add(sc);
            }
            for (SocketChannel channel : channels) {
                // 5. 接收客户端发送的数据
                int read = channel.read(buffer);// 非阻塞，线程仍然会继续运行，如果没有读到数据，read 返回 0
                if (read > 0) {
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    log.debug("after read...{}", channel);
                }
            }
        }
    }
}
